package com.fxb.learn.direct_buff;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author fangjiaxiaobai
 * @date 2022-05-27 16:41
 */
public class Demo {

    public static void main(String[] args) throws IOException {
        String filePath = Demo.class.getResource("").getFile() + "demo.txt";
        System.out.println(filePath);
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");

        FileChannel fileChannel = file.getChannel();

        long length = file.length();
        System.out.println("file.length:" + length);
        System.out.println("fileChannel.size:" + fileChannel.size());
        MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 4 * 1024);

        System.out.println("map.isLoaded:" + byteBuffer.isLoaded());
        System.out.println("capacity: " + byteBuffer.capacity());
        for (int i = 0; i < byteBuffer.limit() - 100; i++) {
            System.out.println("map.get(" + i + "):" + byteBuffer.get());
        }

        System.out.println("写入..");
        FileLock lock = fileChannel.lock();
        byteBuffer.put("dddddd".getBytes(StandardCharsets.UTF_8));
        byteBuffer.force();
        lock.release();

    }

}
